package com.itheima.exception;

import com.itheima.pojo.Result;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result HandlerException(Exception e){
        log.error("出现异常：{}",e.getMessage(),e);
        return Result.error("操作失败");
    }
    @ExceptionHandler(BizException.class)
    public Result HandlerBizException(BizException e){
        log.error("出现异常：{}",e.getMessage(),e);
        return e.toErrorResult();
    }


    @ExceptionHandler(ConstraintViolationException.class)
    public Result handleConstraintViolationException(ConstraintViolationException ex) {
        log.error( "出现异常：{}", ex.getMessage(), ex);
        String s = ex.getConstraintViolations()
                .stream()
                .findFirst()
                .map(ConstraintViolation::getMessage)
                .orElse("参数校验失败");

        return Result.error(s);
    }

    // 处理 @RequestBody @Valid 校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error( "出现异常：{}", ex.getMessage(), ex);
        String s = ex.getBindingResult().getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .findFirst().orElse("参数校验失败");
        return Result.error(s);
    }

}
